package com.team9.fitness.mapper;

import com.team9.fitness.entity.DietRecord;
import org.apache.ibatis.annotations.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 饮食记录映射器
 */
@Mapper
public interface DietRecordMapper {

    @Insert("INSERT INTO diet_record (user_id, food_id, amount, total_calories, total_carbohydrates, " +
            "total_protein, total_fat, meal_time, meal_type, created_at) " +
            "VALUES (#{userId}, #{foodId}, #{amount}, #{totalCalories}, #{totalCarbohydrates}, " +
            "#{totalProtein}, #{totalFat}, #{mealTime}, #{mealType}, NOW())")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(DietRecord dietRecord);

    @Select("SELECT * FROM diet_record WHERE id = #{id}")
    DietRecord selectById(Long id);

    @Select("SELECT dr.*, fi.name as foodName FROM diet_record dr " +
            "LEFT JOIN food_info fi ON dr.food_id = fi.id " +
            "WHERE dr.user_id = #{userId} ORDER BY dr.meal_time DESC")
    List<DietRecord> selectByUserId(Long userId);

    @Select("SELECT dr.*, fi.name as foodName FROM diet_record dr " +
            "LEFT JOIN food_info fi ON dr.food_id = fi.id " +
            "WHERE dr.user_id = #{userId} AND DATE(dr.meal_time) = DATE(#{date}) ORDER BY dr.meal_time DESC")
    List<DietRecord> selectByUserIdAndDate(Long userId, LocalDateTime date);

    @Select("SELECT dr.*, fi.name as foodName FROM diet_record dr " +
            "LEFT JOIN food_info fi ON dr.food_id = fi.id " +
            "WHERE dr.user_id = #{userId} AND dr.meal_type = #{mealType} AND DATE(dr.meal_time) = DATE(#{date}) ORDER BY dr.meal_time DESC")
    List<DietRecord> selectByUserIdAndMealTypeAndDate(Long userId, String mealType, LocalDateTime date);

    @Select("SELECT SUM(total_calories) as totalCalories, SUM(total_carbohydrates) as totalCarbohydrates, " +
            "SUM(total_protein) as totalProtein, SUM(total_fat) as totalFat " +
            "FROM diet_record WHERE user_id = #{userId} AND DATE(meal_time) = DATE(#{date})")
    DietRecord getDailyNutritionSummary(Long userId, LocalDateTime date);

    @Update("UPDATE diet_record SET amount = #{amount}, total_calories = #{totalCalories}, " +
            "total_carbohydrates = #{totalCarbohydrates}, total_protein = #{totalProtein}, " +
            "total_fat = #{totalFat}, meal_time = #{mealTime}, meal_type = #{mealType} WHERE id = #{id}")
    int update(DietRecord dietRecord);

    @Delete("DELETE FROM diet_record WHERE id = #{id}")
    int deleteById(Long id);

    @Delete("DELETE FROM diet_record WHERE user_id = #{userId} AND DATE(meal_time) = DATE(#{date})")
    int deleteByUserIdAndDate(Long userId, LocalDateTime date);
}
